package br.ufpi.util.notification;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import br.com.caelum.vraptor.core.Localization;

/**
 * Velocity Engine Util class
 * 
 * @author EasyTeam, created by Pedro Almir
 *
 */
public class VelocityEngineUtil {

	/**
	 * Get velocity template
	 * @param localization
	 * @param params
	 * @param template
	 * @return the content
	 */
	public static String getTemplate(Localization localization, Map<String, Object> params, String template) {
		try {
			InputStream templateFile = VelocityEngineUtil.class.getResourceAsStream(template);
			
			StringBuilder builder = new StringBuilder();
			int i = 0;
			while ((i = templateFile.read()) != -1) {
				builder.append((char)i);
			}
			templateFile.close();

			VelocityContext context = new VelocityContext();

			for (Entry<String, Object> entry : params.entrySet()) {
				context.put(entry.getKey(), entry.getValue());
			}
			
			context.put("local", getLocalizationMap(localization));

			StringWriter writer = new StringWriter();
			
			Velocity.evaluate(context, writer, "LOG", builder.toString());

			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * Get localization map
	 * @param localization
	 * @return map
	 */
	private static Map<String, String> getLocalizationMap(Localization localization) {
		Map<String, String> result = new HashMap<String, String>();
		for (String k : Collections.list(localization.getBundle().getKeys())) {
			result.put(k, localization.getMessage(k));
		}

		return result;
	}
}
